package com.shizhanzhe.zxbapp.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.shizhanzhe.zxbapp.BuildConfig;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static java.sql.DriverManager.println;

/**
 * Created by YJ on 2018/11/14.
 */
public class DownUtil {
    //获取所有已安装程序包名
    public static List<String> isAvilible(Context context){
        PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0 ; i < packageInfos.size() ; i ++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames;
    }
    //根据包名打开app
    public static void openApp(Context activity, String packageName){
        PackageManager packageManager = activity.getPackageManager();
        Intent intent = new Intent();
        intent = packageManager.getLaunchIntentForPackage(packageName);
        if (intent == null) {
            println("APP not found!");
        }
        activity.startActivity(intent);
    }
    //打开安装包
    public static void installAPK(Context context,File savedFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", savedFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(savedFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}
